<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="4" :sm="24">
              <a-form-item >
                <a-input placeholder="收件人姓名/手机号/订单号" v-model="queryParam.search"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="loadData" icon="search">查询</a-button>
              </span>
            </a-col>
            <a-col :md="2" :sm="24" :offset="14">
              <a-button @click="changeOrderPushStatus(true)" v-if="!timer" type="primary">开始</a-button>
              <a-button @click="changeOrderPushStatus(false)" v-else type="danger">停止接单</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :dataSource="orderList"
        :loading="loading"
        :pagination="{'show-total':total => `共 ${total} 条`,...pagination,current:pagination.pageNo,total:pagination.totalCount,onChange:pageChange}"
      >
        <a-badge :status="orderStatus(record.status)" :text="record | goodsStatusFilter" slot="status" slot-scope="text,record"/>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">详情</a>
            <template v-if="canITake(record)">
              <a-divider type="vertical" />
              <a @click="handleTake(record)">接单</a>
            </template>
          </template>
        </span>
      </a-table>
    </a-card>
    <audio controls="controls" src="http://tcrm.jialexi.top/shop.mp3" ref="audio" style="visibility: hidden;"></audio>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { goodsOrderList, goodsOrderTake, goodsOrderPush } from '@/api/goods'
import orderStatus from '@/mixins/orderStatus'

const columns = [
    {
      title: '名称',
      dataIndex: 'info',
      customRender (info) {
          const infoNames = info.map(item => item.name)
          return infoNames && infoNames.join('\n')
      }
    },
   {
    title: '支付价格',
    dataIndex: 'price',
    customRender (text) {
        return '￥' + text
    }
  },
   {
    title: '数量',
    dataIndex: 'num'
  },
  {
    title: '姓名',
    dataIndex: 'serve_name'
  },
  {
    title: '手机号',
    dataIndex: 'serve_mobile'
  },
  {
    title: '服务地址',
    dataIndex: 'serve_address'
  },
  {
    title: '订单号',
    dataIndex: 'out_trade_no'
  },
  {
    title: '下单时间',
    dataIndex: 'ctime'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'GoodsOrderList',
  mixins: [orderStatus],
  components: {
    STable
  },
  data () {
    this.columns = columns
    return {
      queryParam: {
        search: undefined
      },
      orderList: [],
      loading: false,
      timer: null,
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0,
        totalPage: 0
      },
      loadData: parameter => {
        this.loading = true
        const page = {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        }
        const requestParameters = Object.assign(page, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return goodsOrderList(requestParameters)
          .then(res => {
            this.orderList = res.data.data
            this.pagination = res.data
            delete this.pagination.data
          }).finally(() => (this.loading = false))
      }
    }
  },
  created () {
    this.loadData()
  },
  deactivated () {
    clearTimeout(this.timer)
  },
  beforeDestroy () {
    clearTimeout(this.timer)
  },
  methods: {
    canITake (record) {
      return record.status === 1 && record.is_take <= 2
    },
    pageChange (pageNo) {
      this.pagination.pageNo = pageNo
      this.loadData()
    },
    handleEdit (record) {
      this.$router.push({
        name: 'goodsOrderDetail',
        params: {
          id: record.id
        }
      })
    },
    handleTake (record) {
      this.$confirm({
        title: '你确定要接单吗?',
        // content: '接单',
         onOk: () => {
           goodsOrderTake({ id: record.id }).then(res => {
                this.$refs.table.refresh()
                this.$message.success('操作成功')
            }).catch(() => {})
         }
      })
    },
    setIntervalToOrderPush () {
      this.timer = setTimeout(() => {
        goodsOrderPush().then(res => {
          this.orderList.unshift(res.data)
          this.pagination.totalCount += res.data.length
          this.playAudio()
          this.$notification.success({
            message: '新订单',
            description: '您有新的订单来了,请注意查看!'
          })
        }).finally(() => {
          this.setIntervalToOrderPush()
        })
      }, 60 * 1000)
    },
    changeOrderPushStatus (status) {
      if (status) {
        this.$message.success('开始接单啦')
        this.setIntervalToOrderPush()
      } else {
        clearTimeout(this.timer)
        this.timer = null
        this.$message.success('已停止接单')
      }
    },
    playAudio () {
      this.$refs.audio.play()
    }
  }
}
</script>
